import React, {Component} from 'react';
import logo from '../Images/Logo.jpg';
import style from '../Style/Header.module.scss';
import {Avatar, Menu, Dropdown, message, Modal, Button} from 'antd';
import {DownOutlined, UserOutlined} from '@ant-design/icons';
import axios from "../Api/api";
import defaultUserInfo from '../Images/头像.png';
import {withRouter} from "react-router-dom";
import userInfo from "../Style/userInfo.module.scss";
import {serverLoginPath, serverMainPath} from "../Api/BaseUrl";

class Header extends Component {


    state = {
        isModalVisible: false,
        nickNameChange:'',
        isPasswordVisible:false,
        userdPasswordValue:'',
        changePasswordValue:'',
        OtherchangePasswordValue:'',
        loadings: [],
    }

    constructor(props) {
        super(props);

    }


    /*
    * 退出登录
    * */
    logout() {
        axios.get(serverLoginPath.logOut).then(res => {
            if (res.code === 200) {
                message.success('退出成功', 2, onclose);
                this.props.history.push('/');
                localStorage.clear();
                // console.log(localStorage.getItem("token"))

            } else {
                message.error('退出失败', 2, onclose)
            }
        })
    }

    /*
    * 获取用户信息
    * */
    ShowUserInfo() {
        // console.log(this.props.userInfo);

        this.setState({
            isModalVisible: true,
            nickNameChange:this.props.userInfo.nickname
        })
    }

    modalHandleOk() {
        // this.props.userInfo.nickname
        if(this.props.userInfo.nickname !== this.state.nickNameChange){
            // console.log(this.state.nickNameChange,"[]")
            axios.get(serverMainPath.updateNickName+this.state.nickNameChange+'/'+this.props.userInfo.id).then(res=>{
                if(res.code === 200){
                    message.success('修改昵称成功',1);
                    this.props.userInfo.nickname = this.state.nickNameChange;
                    sessionStorage.clear();
                    axios(serverMainPath.getUserData+this.props.userInfo.id).then(res=>{
                        sessionStorage.setItem('userInfo', JSON.stringify(res.data));
                    })
                }

            })
        }

        this.setState({
            isModalVisible: false
        })
    }

    modalHandleCancel() {
        this.setState({
            isModalVisible: false,
            isPasswordVisible:false,
            userdPasswordValue:'',
            changePasswordValue:'',
            OtherchangePasswordValue:'',
        })
    }
    isChangedNickName(e){
        this.setState({
            nickNameChange:e.target.value
        })
    }
    changePw(){
        this.setState({
            isPasswordVisible: true
        })
    }

    changePasswordHandleOk(){
        let passwordObj= {
            id:this.props.userInfo.id,
            userdPasswordValue:this.state.userdPasswordValue,
            changePasswordValue:this.state.changePasswordValue,
            OtherchangePasswordValue:this.state.OtherchangePasswordValue
        };
        axios.post(serverMainPath.updatePassWord,passwordObj).then(res=>{
            if(res.code === 200){
                message.success('修改成功',1);
                message.info('修改成功',1);

                sessionStorage.clear();
                this.props.history.push('/');
            }else if(res.code===405){
                message.error(res.message,2);

            }else if(res.code === 402){
                message.error(res.message,2);
            }
        })
        this.setState({
            isPasswordVisible: false
        })
    }
    passwordChanged(e){
        let text = e.target.value;
        this.setState({
            userdPasswordValue:text
        })

    }
    userdPasswordChanged(e){
        let text = e.target.value;
        this.setState({
            changePasswordValue:text
        })

    }
    otherUserdPasswordChanged(e){
        let text = e.target.value;
        this.setState({
            OtherchangePasswordValue:text
        })

    }
    enterLoading = (index) => {

        this.setState(({ loadings }) => {
            const newLoadings = [...loadings];
            newLoadings[index] = true;
            return {
                loadings: newLoadings,
            };
        });
        // console.log(serverMainPath.saveContent+this.props.bookContent+'/'+this.props.bookid)
        axios.post(serverMainPath.saveContent,{content:this.props.bookContent,notebook_id:this.props.bookid}).then(res=>{
                console.log(this.props.bookid);
           if(res.code === 200){
               message.success('保存成功',2)
               this.setState(({ loadings }) => {
                   const newLoadings = [...loadings];
                   newLoadings[index] = false;

                   return {
                       loadings: newLoadings,
                   };
               });

               window.location.reload();
           }


        })
        setTimeout(() => {
            this.setState(({ loadings }) => {
                const newLoadings = [...loadings];
                newLoadings[index] = false;

                return {
                    loadings: newLoadings,
                };
            });
        }, 6000);

    };
    render() {
        const menu = (
            <Menu>
                <Menu.Item key="0" onClick={this.ShowUserInfo.bind(this)}>
                    <span>个人信息</span>
                </Menu.Item>
                <Menu.Item key="1" onClick={this.changePw.bind(this)}>
                    <span>修改密码</span>
                </Menu.Item>
                <Menu.Divider/>
                <Menu.Item danger key="3" onClick={this.logout.bind(this)}>退出登录</Menu.Item>
            </Menu>
        );
        const { loadings } = this.state;

        return (
            <div>
                <div className={style.header}>
                    <div className={style.logo}>
                        <img src={logo} alt=""/>
                        <span>Pendo</span>
                    </div>
                    <div className={style.saveContent}>
                       <Button loading={loadings[0]} type='primary' onClick={()=>{this.enterLoading(0)}}>
                           保存
                       </Button>
                    </div>
                    <div className={style.users}>
                        {this.props.userInfo == null ?
                            <Avatar src={defaultUserInfo} shape="square" size='large' icon={<UserOutlined/>}
                                    style={{marginRight: 20 + 'px'}}/> :
                            <Avatar src={this.props.userInfo.avatarpic} shape="square" size='large'
                                    icon={<UserOutlined/>}
                                    style={{marginRight: 20 + 'px'}}/>}

                        <span>
                          <Dropdown overlay={menu} trigger={['click']} placement={"bottomCenter"}>
                                <div>
                                    <DownOutlined/>
                                </div>
                          </Dropdown>
                        </span>
                    </div>
                </div>
                {/*修改信息*/}
                <Modal
                    title="个人信息"
                    visible={this.state.isModalVisible}
                    onOk={this.modalHandleOk.bind(this)}
                    onCancel={this.modalHandleCancel.bind(this)}
                    okText={'保存'}
                    cancelText={'取消'}
                >

                    <div className={userInfo.infoContent}>
                        <div className={userInfo.items}>
                            <div className={userInfo.item}>
                                <div className={userInfo.item_title}>
                                    <span>头像</span>
                                </div>
                                <div className={userInfo.item_content}>
                                    <div className={userInfo.avatar}>
                                        {/*{this.props.userInfo == null ? <img src={defaultUserInfo} alt=""/>:<img src={this.props.userInfo.avatarSrc} alt=""/>}*/}
                                        <img src={defaultUserInfo} alt=""/>
                                    </div>

                                </div>

                            </div>
                            <div className={userInfo.item}>
                                <div className={userInfo.item_title}>
                                    <span>手机号:</span>
                                </div>
                                <div className={userInfo.item_content}>
                                    <p>{this.props.userInfo.phoneNum}</p>
                                </div>

                            </div>
                            <div className={userInfo.item}>
                                <div className={userInfo.item_title}>
                                    <span>昵称:</span>
                                </div>
                                <div className={userInfo.item_content}>
                                    <input type="text"  value={this.state.nickNameChange} onChange={this.isChangedNickName.bind(this)}/>
                                </div>

                            </div>
                            <div className={userInfo.item}>
                                <div className={userInfo.item_title}>
                                    <span>电子邮箱:</span>
                                </div>
                                <div className={userInfo.item_content}>
                                    <p>{this.props.userInfo.email}</p>
                                </div>

                            </div>
                        </div>

                    </div>
                </Modal>
                {/*修改密码*/}
                <Modal
                    title="修改密码"
                    visible={this.state.isPasswordVisible}
                    onOk={this.changePasswordHandleOk.bind(this)}
                    onCancel={this.modalHandleCancel.bind(this)}
                    okText={'保存'}
                    cancelText={'取消'}
                    destroyOnClose="true"
                >

                    <div className={userInfo.infoContent}>
                        <div className={userInfo.items}>
                            <div className={userInfo.passwordItem}>

                                <div className={userInfo.passwordItem_title}>
                                    <span>请输入当前密码：</span>
                                </div>


                                    <div className={userInfo.passwordItem_content}>
                                        <input type="password" value={this.state.userdPasswordValue} onChange={this.passwordChanged.bind(this)} />
                                    </div>


                            </div>

                            <div className={userInfo.passwordItem}>
                                <div className={userInfo.passwordItem_title}>
                                    <span>请输入修改密码：</span>
                                </div>


                                <div className={userInfo.passwordItem_content}>
                                    <input type="password" value={this.state.changePasswordValue} onChange={this.userdPasswordChanged.bind(this)} />
                                </div>

                            </div>
                            <div className={userInfo.passwordItem}>
                                <div className={userInfo.passwordItem_title}>
                                    <span>请再输入修改密码：</span>
                                </div>


                                <div className={userInfo.passwordItem_content}>
                                    <input type="password" value={this.state.OtherchangePasswordValue} onChange={this.otherUserdPasswordChanged.bind(this)}/>
                                </div>

                            </div>

                        </div>

                    </div>
                </Modal>


            </div>
        );
    }
}

export default withRouter(Header);
